package service.app.impl;

import java.sql.Timestamp;

import model.app.AppCreatkey;
import dao.app.AppCreatkeyDao;
import service.app.CreatKeyService;
import util.Time;

public class CreatKeyServiceImpl implements CreatKeyService {
	private AppCreatkeyDao creatkeyDao;
	private int thistime;
	private int expand;
	
	@Override
	public int creatKeyOnly(int type,String timetype,int length){
		return creatNumberCore(type,timetype,length);
	}
	
	@Override
	public int creatKeyOnly(int type){
		return creatNumberCore(type,"YEAR",0);
	}
	
	@Override
	public int creatKeyFull(int type,String timetype,int length){
		return thistime*expand+creatNumberCore(type,timetype,length);
	}
	@Override
	public int creatKeyFull(int type){
		int num=creatNumberCore(type,"MONTH",4);
		return thistime*expand+num;
	}
	
	private synchronized int creatNumberCore(int type,String timetype,int length){
		String ftimetype=null;
		if(timetype.equals("YEAR")){
			ftimetype="yyyy";
		}else if(timetype.equals("MONTH")){
			ftimetype="yyyyMM";
		}
		expand=(int)Math.pow(10,length);		
		
		AppCreatkey c = creatkeyDao.findOne("id",type);
	
		int newnum=isBegin(c.getChangedate(),ftimetype)?(1):(c.getNumber()+1);
		
		c.setNumber(newnum);
		c.setChangedate(Time.CurrentTimestamp());
		
		creatkeyDao.update(c);
		return newnum;
	}
	
	private boolean isBegin(Timestamp t,String f){
		this.thistime=getThisTime(Time.CurrentTimestamp(),f);
		return thistime>getThisTime(t,f);
	}
	
	private int getThisTime(Timestamp thistime,String t){
		return Integer.parseInt(Time.TimeStamp2String(thistime, t));
	}
	
	public AppCreatkeyDao getCreatkeyDao() {
		return creatkeyDao;
	}

	public void setCreatkeyDao(AppCreatkeyDao creatkeyDao) {
		this.creatkeyDao = creatkeyDao;
	}

}
